package view 
{
	import events.MovedObjectEvent;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.TimerEvent;
	
	import model.MGameboard;
	import model.MAsteroid;
	import model.MSpaceship;
	/**
	 * 
	 * @author vkozhaev
	 */
	public class VGameboard extends MovieClip
	{
		
		private var _model:MGameboard;
		private var _vServiceStation:VServiceStation;
		private var _vAsteroidStore:VAsteroidStore;
		private var _asteroids:Vector.<VAsteroid>;
		
		public function VGameboard() 
		{
			
		}
		
		public function set model(val:MGameboard):void {
			this._model = val;
			
			this._model.addEventListener(TimerEvent.TIMER, timerEventHandler);
			
			this._model.addEventListener(MovedObjectEvent.ASTEROID_HAVE_BIN_PROCESSED, removeAsteroid);
			initView(_model);
		}
		
		public function initView(_model:MGameboard):void {
			_vServiceStation = new VServiceStation(_model.serviceStation);
			_vAsteroidStore = new VAsteroidStore(_model.asteroidStore);
			this.addChild(_vServiceStation);
			this.addChild(_vAsteroidStore);
			initAsteroids(_model)
			initSpaceships(_model);
		
		
		}
		
		private function initAsteroids(_model:MGameboard):void {
			var asteroids:Vector.<MAsteroid> = _model.asteroids;
			_asteroids = new Vector.<VAsteroid>();
			for each (var asteroid:model.MAsteroid in asteroids) {
				var vAsteroid:VAsteroid=new VAsteroid(asteroid);
				this.addChild(vAsteroid);
				_asteroids.push(vAsteroid);
			}
		}
		
		private function initSpaceships(_model:MGameboard):void {
			var spaceships:Vector.<MSpaceship> = _model.spaceships;
			for each (var spaceship:MSpaceship in spaceships) {
				var vSpaceship:VSpaceship=new VSpaceship(spaceship);
				this.addChild(vSpaceship);
			}
		}
		
		private function mapEvents(_model:model.MGameboard):void {
			_model.addEventListener(TimerEvent.TIMER, timerEventHandler);
		}
		
		private function removeAsteroid(e:MovedObjectEvent):void {
			var asteroid:model.MAsteroid = e.movedObject as model.MAsteroid;
			var asteroidNum:int = 0;
			for each (var vAsteroid:VAsteroid in _asteroids) {
				
				if (vAsteroid.model == asteroid) {
					this.removeChild(vAsteroid);
					_asteroids.splice(asteroidNum, 1)
					return;
				}
				asteroidNum++;
			}
		}
		
		private function timerEventHandler(e:TimerEvent):void {
			e.updateAfterEvent();
		}
		
	}

}